<template>
  <div class="page-container system-monitor">
    <div v-if="loading" class="loading-spinner">
      <el-progress type="circle" :percentage="100" status="success" :indeterminate="true" :duration="2" />
      <p>正在加载系统数据...</p>
    </div>
    
    <div v-else-if="error" class="error-message">
      <el-alert type="error" :title="'数据加载失败'" :description="error" show-icon :closable="false" />
    </div>

    <div v-else class="page-content">
      <!-- 顶部关键指标 -->
      <el-row :gutter="20" class="summary-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card cpu-card">
            <div class="card-header">
              <el-icon><Odometer /></el-icon>
              <span>CPU 使用率</span>
            </div>
            <div class="card-body">
              <el-progress type="dashboard" :percentage="system.status.cpu_percent || 0" :color="cpuColors" />
              <p class="metric-value">{{ system.status.cpu_percent || 0 }}%</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card memory-card">
            <div class="card-header">
              <el-icon><DataLine /></el-icon>
              <span>内存占用</span>
            </div>
            <div class="card-body">
              <el-progress type="dashboard" :percentage="system.status.memory_percent || 0" :color="memoryColors" />
              <p class="metric-value">{{ formatBytes(system.status.memory_used) }} / {{ formatBytes(system.status.memory_total) }}</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card disk-card">
            <div class="card-header">
              <el-icon><Folder /></el-icon>
              <span>磁盘空间</span>
            </div>
            <div class="card-body">
              <el-progress type="dashboard" :percentage="system.status.disk_percent || 0" :color="diskColors" />
               <p class="metric-value">{{ formatBytes(system.status.disk_used) }} / {{ formatBytes(system.status.disk_total) }}</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="metric-card temp-card">
            <div class="card-header">
               <el-icon><Sunny /></el-icon>
              <span>CPU 温度</span>
            </div>
            <div class="card-body">
              <div class="temp-value">
                <span>{{ system.status.temperature?.toFixed(1) || 'N/A' }}</span>
                <span class="unit">°C</span>
              </div>
              <p class="metric-value">系统核心温度</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 详细信息 -->
      <el-row :gutter="20">
        <!-- 系统信息 -->
        <el-col :span="12">
          <el-card shadow="hover" class="detail-card">
            <template #header>
              <div class="card-header">
                <el-icon><InfoFilled /></el-icon>
                <span>系统信息</span>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="主机名">{{ system.info.hostname }}</el-descriptions-item>
              <el-descriptions-item label="设备ID">{{ system.info.box_id }}</el-descriptions-item>
              <el-descriptions-item label="操作系统">{{ system.info.os }}</el-descriptions-item>
              <el-descriptions-item label="架构">{{ system.info.arch }}</el-descriptions-item>
              <el-descriptions-item label="内核版本" :span="2">{{ system.info.kernel }}</el-descriptions-item>
              <el-descriptions-item label="运行时间" :span="2">{{ formatUptime(system.info.uptime) }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        
        <!-- 负载与网络 -->
        <el-col :span="12">
          <el-card shadow="hover" class="detail-card">
            <template #header>
              <div class="card-header">
                <el-icon><Switch /></el-icon>
                <span>负载与网络</span>
              </div>
            </template>
            <el-descriptions :column="2" border>
               <el-descriptions-item label="系统负载">
                 <el-tag v-for="(load, i) in system.status.loadavg" :key="i" class="load-tag">
                   {{ load.toFixed(2) }}
                 </el-tag>
               </el-descriptions-item>
               <el-descriptions-item label="Swap分区">{{ system.metrics.swap?.percent || 0 }}%</el-descriptions-item>
               <el-descriptions-item label="已发送">{{ formatBytes(system.metrics.network?.bytes_sent || 0) }}</el-descriptions-item>
               <el-descriptions-item label="已接收">{{ formatBytes(system.metrics.network?.bytes_recv || 0) }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 进程列表 -->
       <el-row>
        <el-col :span="24">
          <el-card shadow="hover" class="processes-card">
             <template #header>
              <div class="card-header">
                <el-icon><Grid /></el-icon>
                <span>进程列表 (Top 50)</span>
                 <el-button @click="fetchData" :loading="refreshing" size="small" circle><el-icon><Refresh /></el-icon></el-button>
              </div>
            </template>
            <el-table :data="system.processes" height="400" stripe style="width: 100%">
              <el-table-column prop="pid" label="PID" width="80" sortable />
              <el-table-column prop="name" label="名称" sortable show-overflow-tooltip />
              <el-table-column prop="username" label="用户" width="120" sortable />
              <el-table-column prop="cpu_percent" label="CPU %" width="100" sortable>
                <template #default="scope">{{ scope.row.cpu_percent.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="memory_percent" label="内存 %" width="100" sortable>
                 <template #default="scope">{{ scope.row.memory_percent.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100" sortable />
              <el-table-column prop="create_time" label="启动时间" width="180" sortable>
                <template #default="scope">{{ new Date(scope.row.create_time * 1000).toLocaleString() }}</template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import api from '@/services/api'; 
import { formatBytes, formatUptime } from '@/utils/formatters';

const loading = ref(true);
const refreshing = ref(false);
const error = ref(null);

const system = reactive({
  info: {},
  status: {},
  metrics: {},
  processes: []
});

let intervalId = null;

const cpuColors = [
  { color: '#67C23A', percentage: 60 },
  { color: '#E6A23C', percentage: 80 },
  { color: '#F56C6C', percentage: 100 },
];
const memoryColors = [
  { color: '#409EFF', percentage: 60 },
  { color: '#E6A23C', percentage: 80 },
  { color: '#F56C6C', percentage: 100 },
];
const diskColors = [
  { color: '#909399', percentage: 70 },
  { color: '#E6A23C', percentage: 85 },
  { color: '#F56C6C', percentage: 100 },
];

const fetchData = async () => {
  if(refreshing.value) return;
  refreshing.value = true;
  error.value = null;
  
  try {
    const [infoRes, statusRes, metricsRes, processesRes] = await Promise.all([
      api.getSystemInfo(),
      api.getSystemStatus(),
      api.getSystemMetrics(),
      api.getSystemProcesses()
    ]);

    system.info = infoRes.data.data;
    system.status = statusRes.data;
    system.metrics = metricsRes.data.data;
    system.processes = processesRes.data.data;

  } catch (err) {
    error.value = `无法从后端服务获取数据。请确保后端正在运行并可访问。错误: ${err.message}`;
    ElMessage.error('获取系统数据失败！');
    console.error(err);
    // 如果获取失败，停止轮询
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

onMounted(() => {
  fetchData();
  // 设置定时器，每5秒刷新一次数据
  intervalId = setInterval(fetchData, 5000);
});

onUnmounted(() => {
  // 组件卸载时清除定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>

<style scoped>
.system-monitor {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.summary-cards .metric-card {
  text-align: center;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.summary-cards .metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.metric-card .card-body {
  padding-top: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.metric-card .metric-value {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.temp-card .temp-value {
  font-size: 40px;
  font-weight: bold;
  color: #F56C6C;
}
.temp-card .temp-value .unit {
  font-size: 20px;
  margin-left: 5px;
}

.detail-card, .processes-card {
  margin-top: 20px;
  border-radius: 12px;
}

.load-tag {
  margin-right: 5px;
}

.processes-card .el-table {
  border-radius: 8px;
}
</style> 